import React, { memo, useRef } from "react";
import { Carousel } from "antd";
import classnames from "classnames";
import { useSelector, useDispatch, shallowEqual } from "react-redux";

import "./index.scss";
import radioActions from "store/action/djradio";

const PAGE_SIZE = 16;

const WYRadioCategory = memo(function (props) {
  // data-props
  const carouselRef = useRef();
  // redux
  const { categories, currentId } = useSelector(
    (state) => ({
      categories: state.getIn(["djradio", "categories"]),
      currentId: state.getIn(["djradio", "currentId"]),
    }),
    shallowEqual
  );
  const dispatch = useDispatch();

  // 其它逻辑
  const setCurrentId = (id) => {
    dispatch(radioActions.setCurrentId(id));
  };
  const page = Math.ceil(categories.length / PAGE_SIZE) || 1;
  const getSize = (index) => {
    return index * PAGE_SIZE > categories.length
      ? categories.length
      : index * PAGE_SIZE;
  };

  return (
    <div className="wy-radio-cat">
      <div
        className="arrow arrow-left"
        onClick={(e) => carouselRef.current.prev()}
      ></div>
      {/* 中间部分 */}
      <div className="carousel">
        <Carousel dots={{ className: "dots" }} ref={carouselRef}>
          {Array(page)
            .fill(0)
            .map((_, i) => (
              <div className="category-page" key={i}>
                {categories.length > 0 &&
                  categories
                    .slice(i * PAGE_SIZE, getSize(i + 1))
                    .map((item) => (
                      <div
                        className={classnames(
                          "category-item",
                          item.id === currentId ? "active" : ""
                        )}
                        key={item.pic56x56Id}
                        onClick={(e) => setCurrentId(item.id)}
                      >
                        <div
                          className="image"
                          style={{ backgroundImage: `url(${item.picWebUrl})` }}
                        ></div>
                        <span>{item.name}</span>
                      </div>
                    ))}
              </div>
            ))}
        </Carousel>
      </div>
      <div
        className="arrow arrow-right"
        onClick={(e) => carouselRef.current.next()}
      ></div>
    </div>
  );
});

export default WYRadioCategory;
